package dotdashdot.bradz.trendsettr;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentCreateItemDetail extends Fragment {
	public static final String ARG_ITEM_ID = "item_id";
	private String mItem;
	private ClassNetworkHelper helper;
	private Context self;
	private ClassFonts fonts;
	private ClassUberLogger logger;
	private ClassUserCredentials credentials;
	private ApplicationGlobalVars globals;
	private TextView trend_text, warning_text, trend_text_header, user_name_text_view, user_rank_text_view;
	private ProgressBar progress;
	private Button submit_button;
	private ClassTrendingContainer container;
	private ListView fileList;
	private FragmentActivity frag_activity;
	
	Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 0:
	        	set_loading_elements(false);
	        	create_similar_list();
	            break;
	        case 5:
	        	format_credentials();
	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
	
	public FragmentCreateItemDetail() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		logger = new ClassUberLogger("FragmentCreateItemDetail");
		frag_activity = this.getActivity();
		globals = ((ApplicationGlobalVars) frag_activity.getApplication());
		credentials = new ClassUserCredentials(globals);
		container = new ClassTrendingContainer();

		if (getArguments().containsKey(ARG_ITEM_ID)) {
			mItem = getArguments().getString(ARG_ITEM_ID);
		}
		
		logger.info("OnCreate Finished");
	}

	private void apply_for_credentials(){
		set_loading_elements(true);
		helper.apply_for_credentials(credentials, myHandler);
	}
	
	private void set_loading_elements(boolean loading_something){
		if(loading_something){
			trend_text.setVisibility(View.INVISIBLE);
			trend_text_header.setVisibility(View.INVISIBLE);
			submit_button.setVisibility(View.INVISIBLE);
			warning_text.setVisibility(View.INVISIBLE);
			progress.setVisibility(View.VISIBLE);
	    	logger.info("Still loading...");
		}else{
			trend_text.setVisibility(View.VISIBLE);
			trend_text_header.setVisibility(View.VISIBLE);
			submit_button.setVisibility(View.VISIBLE);
			warning_text.setVisibility(View.VISIBLE);
			progress.setVisibility(View.INVISIBLE);
	    	logger.info("Done loading");
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		logger.info("Creating View");
		
		View rootView = inflater.inflate(R.layout.similar_submit,container, false);
		
		self = this.getActivity();
		fonts = new ClassFonts(self.getAssets());
		
		helper = new ClassNetworkHelper(this.getActivity(),globals);
		
		// Show the dummy content as text in a TextView.
		if (mItem != null) {
			
			logger.info("Received Trend String");
			logger.info(mItem);
			
			trend_text = (TextView) rootView.findViewById(R.id.start_trend_compare_text);
			trend_text_header = (TextView) rootView.findViewById(R.id.start_trend_upper_text);
			warning_text = (TextView) rootView.findViewById(R.id.start_trend_warning_text);
			submit_button = (Button) rootView.findViewById(R.id.start_trend_search_button);
			progress = (ProgressBar) rootView.findViewById(R.id.progress_start);
	    	user_name_text_view = (TextView) rootView.findViewById(R.id.user_name_footer);
	    	user_rank_text_view = (TextView) rootView.findViewById(R.id.user_rank_footer);
	    	fileList = (ListView) rootView.findViewById(android.R.id.list);
	    	((TextView) rootView.findViewById(R.id.top_navigation_text)).setTypeface(fonts.get_font("cond_medium"));
			
			trend_text.setText(mItem);
			
			if(!credentials.logged_in){
				apply_for_credentials();
			}else{
				format_credentials();
			}
		}

		return rootView;
	}
	
	@Override
	public void onStart(){
		super.onStart();
	}
	
	private void format_credentials(){
  		set_loading_elements(true);
    	user_name_text_view.setTypeface(fonts.get_font("medium_italic"));
    	user_rank_text_view.setTypeface(fonts.get_font("medium"));
    	user_name_text_view.setText(credentials.name);
    	user_rank_text_view.setText("Trendsettr Rank: "+credentials.rank);
    	globals.set_credentials_store(credentials);
		helper.get_all_from_network_start_trend(container, myHandler);
    	logger.info("Credentials formatted");
    }
	
	public void construct_graph(){
		logger.info("Reseting new layout");
	}
	
	public void create_similar_list(){
		
		//start_trend_warning_text
		
		ArrayList<String> all_trends = new ArrayList<String>();
    	
        for(ClassTopic topic:container.get_topic_list()){
        	for(ClassTrend trend:topic.get_trend()){
        		all_trends.add(StringUtils.capitalize(trend.get_name()));
        	}
        }
        
        ClassLevenshteinDistance distance = new ClassLevenshteinDistance(all_trends);
        
        //This number is the amount of letters needed to be changed for the trend to equal a trend currently in the list
        int similar_distance = (int) (Math.ceil(mItem.length() / 10) + 2);
        
        ArrayList<String> close_trends = distance.compareTrend(mItem, similar_distance);
        
        logger.info("Printing Similar Trends");
        for(String trend: close_trends){
        	logger.info(trend);
        }
        
        if(all_trends.contains(mItem)){
        	warning_text.setText("Already Exists!");
        	submit_button.setVisibility(View.INVISIBLE);
        }else if(close_trends.size() > 0){
        	warning_text.setText("Similar Found");
            ArrayAdapter compiled_list = new ArrayAdapter<String>(self,R.layout.similar_row, close_trends);
            fileList.setAdapter(compiled_list);
            compiled_list.notifyDataSetChanged();
            submit_button.setVisibility(View.INVISIBLE);
        }
        
    	submit_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	    		pairs.add(new BasicNameValuePair("topicName", "New"));
	    		pairs.add(new BasicNameValuePair("trendName", StringUtils.capitalize(mItem)));
	        	
	        	helper.post_network(pairs, "/trend", myHandler);
	        	
	        	new AlertDialog.Builder(self)
	            .setTitle("Trend Submitted!")
	            .setMessage("Your trend has been submitted and will now be evaluated by our team of crack specialists.")
	            .setPositiveButton("Contiue", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) { 
	                    // continue with delete
	                	frag_activity.finish();
	                }
	             })
	             .show();
            }
        });
        
	}
}
